package com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.*;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.req.SmsEnrollmentManagementStudentInfoBatchReq;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.req.SmsEnrollmentManagementStudentInfoExportReq;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.req.SmsEnrollmentManagementStudentInfoReq;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.resp.SmsEnrollmentManagementStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.resp.SmsEnrollmentManagementTaskResp;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.entity.resp.SmsEnrollmentManagementTeacherInfoResp;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.service.SmsEnrollmentManagementStudentInfoService;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.*;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskNameExample.TASK_NAME_ENROL_STUDENT;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_DONE;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_ERR;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskTypeConstant.TASK_TYPE_ENROL_STUDENT;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.IsCancelStatusConstant.IS_CANCEL_STATUS_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.IsCancelStatusConstant.IS_CANCEL_STATUS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.ReturnVisitStatusConstant.RETURN_VISIT_STATUS_NOT_RETURN;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.ReturnVisitStatusConstant.RETURN_VISIT_STATUS_RETURNED;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.SignMethodConstant.SIGN_METHOD_LINE_SIGN;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.SignMethodConstant.SIGN_METHOD_TEACHER_RECOMMEND;
import static com.xyht.sca_s.student_manage_system.modules.enrollmentManagement.constant.TaskStatusConstant.TASK_STATUS_OPEN;
import static com.xyht.sca_s.student_manage_system.modules.student.constant.StudentInfoCommonConstant.PER_SHEET_NUM;

/**
 * <p>
 * 招生管理学生信息 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-15
 */
@Service
public class SmsEnrollmentManagementStudentInfoServiceImpl extends ServiceImpl<SmsEnrollmentManagementStudentInfoMapper, SmsEnrollmentManagementStudentInfo> implements SmsEnrollmentManagementStudentInfoService {
    @Resource
    private SmsEnrollmentManagementStudentInfoMapper smsEnrollmentManagementStudentInfoMapper;
    @Resource
    private SmsEnrollmentManagementTaskMapper smsEnrollmentManagementTaskMapper;
    @Resource
    private SmsEnrollmentManagementCollegeMajorMapper smsEnrollmentManagementCollegeMajorMapper;
    @Resource
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Resource
    private SmsImportTaskMapper smsImportTaskMapper;
    @Resource
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private SmsEnrollmentManagementTeacherInfoMapper smsEnrollmentManagementTeacherInfoMapper;
    @Resource
    private SmsEnrollmentManagementOrgSettingMapper smsEnrollmentManagementOrgSettingMapper;
    @Resource
    private PlatformTransactionManager transactionManager;

    @Override
    public ResponseResult addEnrollmentManagementStudentInfo(SmsEnrollmentManagementStudentInfoReq studentInfoReq) {
        if (isNullOrEmpty(studentInfoReq.getStudentName(),
                studentInfoReq.getStudentSex(), studentInfoReq.getStudentContact(),
                studentInfoReq.getCollegeId(), studentInfoReq.getMajorId(),
                studentInfoReq.getSignMethod(),
                studentInfoReq.getEnrollmentType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (!studentInfoReq.getSignMethod().equals(SIGN_METHOD_LINE_SIGN) &&
                !studentInfoReq.getSignMethod().equals(SIGN_METHOD_TEACHER_RECOMMEND)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (studentInfoReq.getSignMethod().equals(SIGN_METHOD_TEACHER_RECOMMEND)) {
            if (isNullOrEmpty(studentInfoReq.getEnrollmentTeacher())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //校验身份证
//        if (!isNullOrEmpty(studentInfoReq.getStudentIdCard()) && !isValidIDCard(studentInfoReq.getStudentIdCard())) {
//            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_ID_CARD_ERR);
//        }

        //检测招生计划
        Date nowDate = new Date();
        List<SmsEnrollmentManagementTask> list = smsEnrollmentManagementTaskMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementTask>()
                .eq(SmsEnrollmentManagementTask::getTaskStatus, TASK_STATUS_OPEN)
                .le(SmsEnrollmentManagementTask::getTaskBgTime, nowDate)
                .ge(SmsEnrollmentManagementTask::getTaskEndTime, nowDate)
        );
        if (list == null || list.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_TASK_NOT_ON_USE);
        }
        SmsEnrollmentManagementTask task = list.get(0);

        //检测用户是否已录入当前计划
//        List<SmsEnrollmentManagementStudentInfo> studentInfoList = smsEnrollmentManagementStudentInfoMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementStudentInfo>()
//                .eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTaskId, task.getId())
//                .and(wrapper -> {
//                    wrapper.eq(SmsEnrollmentManagementStudentInfo::getStudentContact, studentInfoReq.getStudentContact());
//                    if (!isNullOrEmpty(studentInfoReq.getStudentIdCard())){
//                        wrapper.or().eq(SmsEnrollmentManagementStudentInfo::getStudentIdCard, studentInfoReq.getStudentIdCard());
//                    }
//                })
//        );
//        if (studentInfoList != null && studentInfoList.size() > 0) {
//            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_EXIST);
//        }

        //检测招生计划院系专业
        List<SmsEnrollmentManagementCollegeMajor> collegeMajorList = smsEnrollmentManagementCollegeMajorMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementCollegeMajor>()
                .eq(SmsEnrollmentManagementCollegeMajor::getTaskId, task.getId())
                .eq(SmsEnrollmentManagementCollegeMajor::getCollegeId, studentInfoReq.getCollegeId())
                .eq(SmsEnrollmentManagementCollegeMajor::getMajorId, studentInfoReq.getMajorId()));
        if (collegeMajorList == null || collegeMajorList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_COLLEGE_MAJOR_NOT_ON_USE);
        }

        SmsEnrollmentManagementOrgSetting college = smsEnrollmentManagementOrgSettingMapper.selectById(studentInfoReq.getCollegeId());
        SmsEnrollmentManagementOrgSetting major = smsEnrollmentManagementOrgSettingMapper.selectById(studentInfoReq.getMajorId());
        if (college == null || major == null) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsEnrollmentManagementStudentInfo addStudentInfo = new SmsEnrollmentManagementStudentInfo();
        BeanUtils.copyProperties(studentInfoReq, addStudentInfo);
        addStudentInfo.setCollegeName(college.getOrgName());
        addStudentInfo.setMajorName(major.getOrgName());
        addStudentInfo.setReturnVisitStatus(RETURN_VISIT_STATUS_NOT_RETURN);
        addStudentInfo.setSignTime(nowDate);
        addStudentInfo.setEnrollmentTaskId(task.getId());
        addStudentInfo.setEnrollmentType(studentInfoReq.getEnrollmentType());
        smsEnrollmentManagementStudentInfoMapper.insert(addStudentInfo);
        return CommonResult.success();
    }

    @Override
    @Async
    public Future<ResponseResult> batchEnrollmentManagementStudentInfo(SmsEnrollmentManagementStudentInfoBatchReq studentInfoBatchReq, String user_id) {
        if (isNullOrEmpty(studentInfoBatchReq.getSignTime(), studentInfoBatchReq.getEnrollmentType(),
                studentInfoBatchReq.getEnrollmentTeacher(), studentInfoBatchReq.getSignMethod())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }

        if (studentInfoBatchReq.getStudentInfoList() == null || studentInfoBatchReq.getStudentInfoList().size() < 1) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }

        //检测招生计划
        List<SmsEnrollmentManagementTask> list = smsEnrollmentManagementTaskMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementTask>()
                .eq(SmsEnrollmentManagementTask::getTaskStatus, TASK_STATUS_OPEN));
        if (list == null || list.size() < 1) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_TASK_NOT_ON_USE));
        }
        SmsEnrollmentManagementTask task = list.get(0);
        studentInfoBatchReq.setEnrollmentTaskId(task.getId());

        //创建导入任务
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setTaskName(TASK_NAME_ENROL_STUDENT);
        smsImportTask.setUserId(user_id);
        smsImportTask.setTaskType(TASK_TYPE_ENROL_STUDENT);
        smsImportTaskMapper.insert(smsImportTask);
        batchAddEnrolStudentInfo(studentInfoBatchReq, smsImportTask.getId());
        return new AsyncResult<>(CommonResult.success());
    }

    private void batchAddEnrolStudentInfo(SmsEnrollmentManagementStudentInfoBatchReq studentInfoBatchReq, String id) {
        int OFFSET_ROW = 2;
        int task_status = TASK_STATUS_DONE;
        for (int i = 0; i < studentInfoBatchReq.getStudentInfoList().size(); i++) {
            //开启事务
            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
            // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 设置嵌套事务
            TransactionStatus status = transactionManager.getTransaction(dt);
            try {
                SmsEnrollmentManagementStudentInfoReq studentInfo = studentInfoBatchReq.getStudentInfoList().get(i);
                if (isNullOrEmpty(studentInfo.getStudentName(), studentInfo.getStudentContact(),
                        studentInfo.getCollegeName(), studentInfo.getMajorName(),
                        studentInfo.getSingleOrUnifiedRecruitment(), studentInfo.getUnifiedAdmissionOrSelfAdmission())) {
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_INVALID_PARAM, (i + OFFSET_ROW) + "");
                    continue;
                }

                //校验身份证
//                if (!isNullOrEmpty(studentInfo.getStudentIdCard()) && !isValidIDCard(studentInfo.getStudentIdCard())) {
//                    task_status = TASK_STATUS_ERR;
//                    createTeacherImportTaskDetail(id, REASON_NEW_STUDENT_ID_CARD_FORMAT_ERROR, (i + OFFSET_ROW) + "");
//                    continue;
//                }

                List<SmsEnrollmentManagementOrgSetting> collegeList = smsEnrollmentManagementOrgSettingMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementOrgSetting>()
                        .eq(SmsEnrollmentManagementOrgSetting::getOrgName, studentInfo.getCollegeName()));
                if (collegeList == null || collegeList.size() < 1) {
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_ORG_COLLEGE_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }

                List<SmsEnrollmentManagementOrgSetting> majorList = smsEnrollmentManagementOrgSettingMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementOrgSetting>()
                        .eq(SmsEnrollmentManagementOrgSetting::getOrgName, studentInfo.getMajorName()));
                if (majorList == null || majorList.size() < 1) {
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_ORG_MAJOR_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }

                //检测用户是否已录入当前计划
//                List<SmsEnrollmentManagementStudentInfo> studentInfoList = smsEnrollmentManagementStudentInfoMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementStudentInfo>()
//                        .eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTaskId, studentInfoBatchReq.getEnrollmentTaskId())
//                        .and(wrapper -> {
//                            wrapper.eq(SmsEnrollmentManagementStudentInfo::getStudentContact, studentInfo.getStudentContact());
//                            if (!isNullOrEmpty(studentInfo.getStudentIdCard())){
//                                wrapper.or().eq(SmsEnrollmentManagementStudentInfo::getStudentIdCard, studentInfo.getStudentIdCard());
//                            }
//                        })
//                );
//                if (studentInfoList != null && studentInfoList.size() > 0) {
//                    task_status = TASK_STATUS_ERR;
//                    createTeacherImportTaskDetail(id, REASON_TEL_ID_CARD_HAS_SIGN, (i + OFFSET_ROW) + "");
//                    continue;
//                }

                SmsEnrollmentManagementStudentInfo addEnrolStudent = new SmsEnrollmentManagementStudentInfo();
                BeanUtils.copyProperties(studentInfo, addEnrolStudent);

                if (!isNullOrEmpty(addEnrolStudent.getStudentProvinces())) {
                    int index = addEnrolStudent.getStudentProvinces().lastIndexOf("省");
                    if (index > 0) {
                        String suffix = addEnrolStudent.getStudentProvinces().substring(0, index);
                        addEnrolStudent.setStudentProvinces(suffix);
                    }
                }

                if (!isNullOrEmpty(addEnrolStudent.getStudentCity())) {
                    int index = addEnrolStudent.getStudentCity().lastIndexOf("市");
                    if (index > 0) {
                        String suffix = addEnrolStudent.getStudentCity().substring(0, index);
                        addEnrolStudent.setStudentCity(suffix);
                    }
                }

                if (!isNullOrEmpty(addEnrolStudent.getStudentCounty())) {
                    int index = addEnrolStudent.getStudentCounty().lastIndexOf("县");
                    if (index > 0) {
                        String suffix = addEnrolStudent.getStudentCounty().substring(0, index);
                        addEnrolStudent.setStudentCounty(suffix);
                    }
                }

                addEnrolStudent.setSignTime(studentInfoBatchReq.getSignTime());
                addEnrolStudent.setEnrollmentTeacher(studentInfoBatchReq.getEnrollmentTeacher());
                addEnrolStudent.setEnrollmentTaskId(studentInfoBatchReq.getEnrollmentTaskId());
                addEnrolStudent.setSignMethod(studentInfoBatchReq.getSignMethod());
                addEnrolStudent.setCollegeId(collegeList.get(0).getId().toString());
                addEnrolStudent.setMajorId(majorList.get(0).getId().toString());
                addEnrolStudent.setEnrollmentType(studentInfoBatchReq.getEnrollmentType());
                smsEnrollmentManagementStudentInfoMapper.insert(addEnrolStudent);

                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
                task_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(id, REASON_IMPORT_ERR, (i + OFFSET_ROW) + "");
            } finally {
                if (status.isNewTransaction() && !status.isCompleted()) {
                    transactionManager.commit(status);
                }
            }

        }
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setId(id);
        smsImportTask.setStatus(task_status);
        smsImportTaskMapper.updateById(smsImportTask);
    }

    private void createTeacherImportTaskDetail(String id, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(id);
        smsImportTaskDetail.setFailReason(reason);
        smsImportTaskDetail.setFailRow(row);
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }

    @Override
    public ResponseResult deleteEnrollmentManagementStudentInfo(SmsEnrollmentManagementStudentInfoReq studentInfoReq) {
        if (isNullOrEmpty(studentInfoReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        smsEnrollmentManagementStudentInfoMapper.deleteById(studentInfoReq.getId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateEnrollmentManagementStudentInfo(SmsEnrollmentManagementStudentInfoReq studentInfoReq) {
        if (isNullOrEmpty(studentInfoReq.getId(), studentInfoReq.getStudentName(),
                studentInfoReq.getCollegeId(), studentInfoReq.getMajorId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsEnrollmentManagementStudentInfo enrollmentStudentInfo = smsEnrollmentManagementStudentInfoMapper.selectById(studentInfoReq.getId());
        if (enrollmentStudentInfo == null) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_NOT_EXIST);
        }

        //手机号变动，检测是否有重复手机号
        if (!enrollmentStudentInfo.getStudentContact().equals(studentInfoReq.getStudentContact())) {
            //检测用户是否已录入当前计划
            List<SmsEnrollmentManagementStudentInfo> studentInfoList = smsEnrollmentManagementStudentInfoMapper.selectList(new LambdaQueryWrapper<SmsEnrollmentManagementStudentInfo>()
                    .eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTaskId, enrollmentStudentInfo.getEnrollmentTaskId())
                    .eq(SmsEnrollmentManagementStudentInfo::getStudentContact, studentInfoReq.getStudentContact()));
            if (studentInfoList != null && studentInfoList.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_EXIST);
            }
        }

        SmsEnrollmentManagementOrgSetting college = smsEnrollmentManagementOrgSettingMapper.selectById(studentInfoReq.getCollegeId());
        SmsEnrollmentManagementOrgSetting major = smsEnrollmentManagementOrgSettingMapper.selectById(studentInfoReq.getMajorId());
        if (college == null || major == null) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsEnrollmentManagementStudentInfo updateStudentInfo = new SmsEnrollmentManagementStudentInfo();
        BeanUtils.copyProperties(studentInfoReq, updateStudentInfo);
        updateStudentInfo.setCollegeName(college.getOrgName());
        updateStudentInfo.setMajorName(major.getOrgName());
        smsEnrollmentManagementStudentInfoMapper.updateById(updateStudentInfo);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getEnrollmentManagementStudentInfoList(String searchStr, Integer signMethod, String enrollmentTeacherId,
                                                                 String collegeId, String majorId, String returnVisitTeacherId,
                                                                 String sex, Integer isCancel, String taskId, Integer enrollmentType,
                                                                 Integer singleOrUnifiedRecruitment,Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<SmsEnrollmentManagementStudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (!isNullOrEmpty(searchStr)) {
            queryWrapper.and(wrapper -> {
                wrapper.like(SmsEnrollmentManagementStudentInfo::getStudentName, searchStr)
                        .or()
                        .like(SmsEnrollmentManagementStudentInfo::getStudentContact, searchStr)
                        .or()
                        .like(SmsEnrollmentManagementStudentInfo::getStudentIdCard, searchStr)
                        .or()
                        .like(SmsEnrollmentManagementStudentInfo::getStudentNation, searchStr);
            });
        }
        if (!isNullOrEmpty(signMethod)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getSignMethod, signMethod);
        }
        if (!isNullOrEmpty(enrollmentTeacherId)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTeacher, enrollmentTeacherId);
        }
        if (!isNullOrEmpty(collegeId)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getCollegeId, collegeId);
        }
        if (!isNullOrEmpty(majorId)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getMajorId, majorId);
        }
        if (!isNullOrEmpty(returnVisitTeacherId)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getReturnVisitTeacher, returnVisitTeacherId);
        }
        if (!isNullOrEmpty(sex)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getStudentSex, sex);
        }
        if (!isNullOrEmpty(isCancel)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getIsCancel, isCancel);
        }
        if (!isNullOrEmpty(taskId)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTaskId, taskId);
        }
        if (!isNullOrEmpty(enrollmentType)) {
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentType, enrollmentType);
        }
        if (!isNullOrEmpty(singleOrUnifiedRecruitment)){
            queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getSingleOrUnifiedRecruitment,singleOrUnifiedRecruitment);
        }
        queryWrapper.orderByDesc(SmsEnrollmentManagementStudentInfo::getCreateTime);
        Page<SmsEnrollmentManagementStudentInfo> page = new Page<>(pageNum, pageSize);

        smsEnrollmentManagementStudentInfoMapper.selectPage(page, queryWrapper);

        List<SmsEnrollmentManagementStudentInfoResp> list = page.getRecords()
                .stream()
                .map(studentInfo -> {
                    SmsEnrollmentManagementStudentInfoResp studentInfoResp = new SmsEnrollmentManagementStudentInfoResp();
                    BeanUtils.copyProperties(studentInfo, studentInfoResp);

                    if (!isNullOrEmpty(studentInfo.getEnrollmentTeacher())) {
                        SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(studentInfo.getEnrollmentTeacher());
                        if (teacherInfo != null) {
                            SmsEnrollmentManagementTeacherInfoResp teacherInfoResp = new SmsEnrollmentManagementTeacherInfoResp();
                            BeanUtils.copyProperties(teacherInfo, teacherInfoResp);
                            studentInfoResp.setEnrollmentTeacherInfo(teacherInfoResp);
                        }
                    }

                    if (!isNullOrEmpty(studentInfo.getReturnVisitTeacher())) {
                        SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(studentInfo.getReturnVisitTeacher());
                        if (teacherInfo != null) {
                            SmsEnrollmentManagementTeacherInfoResp teacherInfoResp = new SmsEnrollmentManagementTeacherInfoResp();
                            BeanUtils.copyProperties(teacherInfo, teacherInfoResp);
                            studentInfoResp.setReturnVisitTeacherInfo(teacherInfoResp);
                        }
                    }

                    SmsEnrollmentManagementTask task = smsEnrollmentManagementTaskMapper.selectById(studentInfo.getEnrollmentTaskId());
                    if (task != null) {
                        SmsEnrollmentManagementTaskResp taskResp = new SmsEnrollmentManagementTaskResp();
                        BeanUtils.copyProperties(task, taskResp);
                        studentInfoResp.setTaskInfo(taskResp);
                    }

                    return studentInfoResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(list, total);
    }

    @Override
    public ResponseResult getEnrollmentManagementStudentInfoDetail(String id) {
        SmsEnrollmentManagementStudentInfo studentInfo = smsEnrollmentManagementStudentInfoMapper.selectById(id);
        if (studentInfo == null) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_NOT_EXIST);
        }

        SmsEnrollmentManagementStudentInfoResp studentInfoResp = new SmsEnrollmentManagementStudentInfoResp();
        BeanUtils.copyProperties(studentInfo, studentInfoResp);

        if (!isNullOrEmpty(studentInfo.getEnrollmentTeacher())) {
            SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(studentInfo.getEnrollmentTeacher());
            if (teacherInfo != null) {
                SmsEnrollmentManagementTeacherInfoResp teacherInfoResp = new SmsEnrollmentManagementTeacherInfoResp();
                BeanUtils.copyProperties(teacherInfo, teacherInfoResp);
                studentInfoResp.setEnrollmentTeacherInfo(teacherInfoResp);
            }
        }

        if (!isNullOrEmpty(studentInfo.getReturnVisitTeacher())) {
            SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(studentInfo.getReturnVisitTeacher());
            if (teacherInfo != null) {
                SmsEnrollmentManagementTeacherInfoResp teacherInfoResp = new SmsEnrollmentManagementTeacherInfoResp();
                BeanUtils.copyProperties(teacherInfo, teacherInfoResp);
                studentInfoResp.setReturnVisitTeacherInfo(teacherInfoResp);
            }
        }

        SmsEnrollmentManagementTask task = smsEnrollmentManagementTaskMapper.selectById(studentInfo.getEnrollmentTaskId());
        if (task != null) {
            SmsEnrollmentManagementTaskResp taskResp = new SmsEnrollmentManagementTaskResp();
            BeanUtils.copyProperties(task, taskResp);
            studentInfoResp.setTaskInfo(taskResp);
        }
        return CommonResult.success(studentInfoResp);
    }

    @Override
    public ResponseResult cancelStudentInfo(SmsEnrollmentManagementStudentInfoReq studentInfoReq) {
        if (isNullOrEmpty(studentInfoReq.getIsCancel(), studentInfoReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (!studentInfoReq.getIsCancel().equals(IS_CANCEL_STATUS_FALSE)
                && !studentInfoReq.getIsCancel().equals(IS_CANCEL_STATUS_TRUE)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsEnrollmentManagementStudentInfo studentInfo = smsEnrollmentManagementStudentInfoMapper.selectById(studentInfoReq.getId());
        if (studentInfo == null) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_NOT_EXIST);
        }
        SmsEnrollmentManagementStudentInfo updateStudentInfo = new SmsEnrollmentManagementStudentInfo();
        updateStudentInfo.setId(studentInfoReq.getId());
        updateStudentInfo.setIsCancel(studentInfoReq.getIsCancel());
        smsEnrollmentManagementStudentInfoMapper.updateById(updateStudentInfo);
        return CommonResult.success();
    }


    @Resource
    private ApiModelUtil apiModelUtil;

    @Override
    public Future<ResponseResult> exportEnrollmentManagementStudentInfoList(SmsEnrollmentManagementStudentInfoExportReq req, HttpServletResponse response) {
        try {
            LambdaQueryWrapper<SmsEnrollmentManagementStudentInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!isNullOrEmpty(req.getSearchStr())) {
                queryWrapper.and(wrapper -> {
                    wrapper.like(SmsEnrollmentManagementStudentInfo::getStudentName, req.getSearchStr())
                            .or()
                            .like(SmsEnrollmentManagementStudentInfo::getStudentContact, req.getSearchStr())
                            .or()
                            .like(SmsEnrollmentManagementStudentInfo::getStudentIdCard, req.getSearchStr())
                            .or()
                            .like(SmsEnrollmentManagementStudentInfo::getStudentNation, req.getSearchStr());
                });
            }
            if (!isNullOrEmpty(req.getSignMethod())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getSignMethod, req.getSignMethod());
            }
            if (!isNullOrEmpty(req.getEnrollmentTeacherId())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTeacher, req.getEnrollmentTeacherId());
            }
            if (!isNullOrEmpty(req.getCollegeId())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getCollegeId, req.getCollegeId());
            }
            if (!isNullOrEmpty(req.getMajorId())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getMajorId, req.getMajorId());
            }
            if (!isNullOrEmpty(req.getReturnVisitTeacherId())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getReturnVisitTeacher, req.getReturnVisitTeacherId());
            }
            if (!isNullOrEmpty(req.getSex())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getStudentSex, req.getSex());
            }
            if (!isNullOrEmpty(req.getIsCancel())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getIsCancel, req.getIsCancel());
            }
            if (!isNullOrEmpty(req.getTaskId())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentTaskId, req.getTaskId());
            }
            if (!isNullOrEmpty(req.getEnrollmentType())) {
                queryWrapper.eq(SmsEnrollmentManagementStudentInfo::getEnrollmentType, req.getEnrollmentType());
            }
            queryWrapper.orderByDesc(SmsEnrollmentManagementStudentInfo::getCreateTime);
            List<SmsEnrollmentManagementStudentInfo> list = smsEnrollmentManagementStudentInfoMapper.selectList(queryWrapper);
            //表头数据
            String[] header = req.getLimitColumn().toArray(new String[0]);
            double sheetNum;
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (list != null && list.size() > 0) {
                sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);
                for (int k = 0; k < sheetNum; k++) {
                    //生成一个表格，设置表格名称为"资源导出表"
                    HSSFSheet sheet = workbook.createSheet("导出表" + (k + 1));

                    //设置表格列宽度为10个字节
                    sheet.setDefaultColumnWidth(12);
                    //创建标题的显示样式
                    HSSFCellStyle headerStyle = workbook.createCellStyle();
                    headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                    HSSFFont f = workbook.createFont();
                    f.setFontHeightInPoints((short) 10);//字号
                    f.setBold(true);//加粗
                    headerStyle.setFont(f);
                    //创建第一行表头
                    HSSFRow headrow = sheet.createRow(0);

                    //遍历添加表头
                    for (int i = 0; i < header.length + 1; i++) {
                        //创建一个单元格
                        HSSFCell cell = headrow.createCell(i);

                        if (i == 0) {
                            //创建一个内容对象
                            HSSFRichTextString text = new HSSFRichTextString("序号");
                            //将内容对象的文字内容写入到单元格中
                            cell.setCellValue(text);
                            cell.setCellStyle(headerStyle);
                            continue;
                        }
                        //创建一个内容对象
                        String header1 = apiModelUtil.getFieldValueByFieldName(SmsEnrollmentManagementStudentInfo.class, header[i - 1]);
                        HSSFRichTextString text = new HSSFRichTextString(header1);

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    int range = PER_SHEET_NUM;
                    if (k + 1 == sheetNum) {
                        range = list.size() - (PER_SHEET_NUM) * k;
                    }
                    for (int i = 0; i < range; i++) {
                        //创建一行
                        HSSFRow row1 = sheet.createRow(i + 1);
                        SmsEnrollmentManagementStudentInfo studentInfo = list.get((PER_SHEET_NUM) * k + i);
                        Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(studentInfo), Map.class);
                        row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                        for (int j = 0; j < header.length; j++) {
                            String rowContent = "";
                            if (map.get(header[j]) instanceof Integer) {
                                Integer value = (Integer) map.get(header[j]);
                                if (value == null) {
                                    rowContent = "";
                                } else if (header[j].equals("signMethod")) {
                                    rowContent = value.equals(SIGN_METHOD_LINE_SIGN) ? "线上报名" : "线下教师推荐";
                                } else if (header[j].equals("returnVisitStatus")) {
                                    rowContent = value.equals(RETURN_VISIT_STATUS_RETURNED) ? "已回访" : "未回访";
                                } else if (header[j].equals("isCancel")) {
                                    rowContent = value.equals(IS_CANCEL_STATUS_TRUE) ? "作废" : "正常";
                                } else if (header[j].equals("singleOrUnifiedRecruitment")) {
                                    rowContent = value.equals(1) ? "单招" : "统招";
                                } else if (header[j].equals("unifiedAdmissionOrSelfAdmission")) {
                                    rowContent = value.equals(1) ? "统一录取" : "自主招生";
                                }
                                row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                                continue;
                            }

                            if (map.get(header[j]) instanceof String) {
                                String value = (String) map.get(header[j]);
                                if (value == null) {
                                    rowContent = "";
                                } else if (header[j].equals("enrollmentTeacher")) {
                                    SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(value);
                                    if (teacherInfo != null){
                                        rowContent = teacherInfo.getTeacherName();
                                    }else{
                                        rowContent = "";
                                    }
                                } else if (header[j].equals("returnVisitTeacher")) {
                                    SmsEnrollmentManagementTeacherInfo teacherInfo = smsEnrollmentManagementTeacherInfoMapper.selectById(value);
                                    if (teacherInfo != null){
                                        rowContent = teacherInfo.getTeacherName();
                                    }else{
                                        rowContent = "";
                                    }
                                } else {
                                    rowContent = value;
                                }
                                row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                                continue;
                            }


                            if (map.get(header[j]) instanceof Long) {
                                rowContent = TimeUtil.DateHanZiSimpleTimestamp((long) map.get(header[j]));
                            } else {
                                rowContent = (String) map.get(header[j]);
                            }
                            row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                        }
                    }
                }
            }

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("导出表.xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode("导出表.xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return new AsyncResult<>(CommonResult.success());
    }
}
